import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { ToolsService } from 'src/utils/tools.service';
import { Repository, TreeRepository, DataSource } from 'typeorm';
import { CreateAccessDto } from './dto/create-access.dto';
import { UpdateAccessDto } from './dto/update-access.dto';
import { AccessEntity } from './entities/access.entity';

@Injectable()
export class AccessService {
  @InjectRepository(AccessEntity)
  private readonly accessRepository: Repository<AccessEntity>;
  @InjectRepository(AccessEntity)
  private readonly treeAccessRepository: TreeRepository<AccessEntity>;
  @InjectDataSource()
  private readonly dataSource: DataSource;

  async create(createAccessDto: CreateAccessDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务
      const parent = await this.accessRepository
        .createQueryBuilder('access')
        .where('access.id = :id', { id: createAccessDto.id })
        .getOne();
      const access = new AccessEntity();
      access.module_name = createAccessDto.module_name;
      access.url = createAccessDto.url;
      access.type = 2;
      if (parent) {
        access.parent = parent;
      }
      await manager.save(access);
      return access;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async findAll(parentId: string) {
    try {
      const trees = await this.treeAccessRepository.findTrees();
      return trees;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} access`;
  }

  async update(id: string, updateAccessDto: UpdateAccessDto) {
    const queryRunner = this.dataSource.createQueryRunner();
    try {
      const manager = await queryRunner.manager; //使用事务
      const access = new AccessEntity();
      access.id = id;
      access.module_name = updateAccessDto.module_name;
      access.url = updateAccessDto.url;
      await manager.save(access);
      return access;
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  async remove(id: string) {
    await this.accessRepository
      .createQueryBuilder()
      .from(AccessEntity, 'access')
      .where('access.id = :id', { id: id })
      .delete()
      .execute();
    return '删除成功';
  }
}
